<?php

namespace app\index\controller;
use think\facade\Hook;
use mqtt\phpMQTT;
use Bluerhinos\phpMQTT as MqttClient;

class Mqtt
{
    public function index()
    {
        return 1356;
    }

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    // 请求地址1：http://www.mytp5.com/index.php/index/Mqtt/publishMQ
    // 请求地址2：http://www.mytp5.com/index/Mqtt/publishMQ
    public function publishMQ()
    {
        //$mqtt = new phpMQTT("111.230.25.120", 1883, "hacker");
        //
        //if ($mqtt->connect()) {
        //
        //    $content = "are you ok";
        //
        //    $mqtt->publish("mytest",$content,0);
        //    $mqtt->close();
        //
        //    return 1;
        //}
        //
        //return 0;

        $server   = '111.230.25.120';
        $port     = 1883;
        $clientId = 'test-publisher';

        //$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
        //$mqtt->connect();
        //$re = $mqtt->publish('mytest', 'Hello World!', 0);

        $mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);

        $mqtt->connect();

        $re = $mqtt->publish('mytest', 'Hello World!', 0);
        //$mqtt->disconnect();

        return $re;
    }

    // 请求地址2：http://www.mytp5.com/index/Mqtt/mqttClient
    public function mqttClient()
    {
        $host = "111.230.25.120"; // 主机
        $port = 1883; // 端口
        $username = ""; // 如果没有则为空
        $password = ""; // 如果没有则为空
        //$message = "Hello CloudMQTT!"; // 要发送的消息

        $message = json_encode([
            "name" => "theme",
            "title" => "top",
            "count" => 20,
            "weather" => "windy"
        ]);

        // phpMQTT 有四个参数：主机，端口，客户端id，证书。官网这里的案例没写证书，请参考phpMQTT类
        // 没有证书的时候只能连接1883端口，不能连接8883端口。
        $mqtt = new MqttClient($host, $port, "ClientID".rand());
        // 连接
        if ($mqtt->connect()) {
            $mqtt->publish("mytest",$message, 0);
            $mqtt->close(); // 关闭
        }else{
            echo "Fail or time out<br />";
        }

    }

}
